package xyz.zhouxf.rpc.registry.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxf.rpc.loadbalance.LoadBalancer;
import xyz.zhouxf.rpc.registry.ServiceDiscovery;
import xyz.zhouxf.rpc.util.NacosUtil;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author zhouxf
 * @date 2022/9/2
 */
@Slf4j
public class NacosServiceDiscovery implements ServiceDiscovery {


    private final LoadBalancer loadBalancer;

    public NacosServiceDiscovery(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
    }
    /**
     * @param serviceName
     * @return
     */
    @Override
    public InetSocketAddress findService(String serviceName) {
        try {
            List<Instance> instanceList = NacosUtil.getAllInstances(serviceName);
            Instance instance = instanceList.get(0);
            InetSocketAddress inetSocketAddress = new InetSocketAddress(instance.getIp(),instance.getPort());
            return inetSocketAddress;
        } catch (NacosException e) {
            log.error("服务发现失败：{}",e);
        }
        return null;
    }
}
